package com.taiyuan.tongcheng.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.os.Environment;
import android.provider.Settings.Secure;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;


public class CommonUtil {

    public static String[] bytesToHexStrings(byte[] src){       

           if (src == null || src.length <= 0) {       

               return null;       

           }

           String[] str = new String[src.length];

           

           for (int i = 0; i < src.length; i++) {       

               int v = src[i] & 0xFF;       

               String hv = Integer.toHexString(v);       

               if (hv.length() < 2) {       

                   str[i] = "0";       

               }       

               str[i] = hv;        

           }       

           return str;       

       }
    
    
    /** 

     * byte����ת����16�����ַ��� 

     * @param src 

     * @return 

     */  

    public static String bytesToHexString(byte[] src){       

           StringBuilder stringBuilder = new StringBuilder();       

           if (src == null || src.length <= 0) {       

               return null;       

           }       

           for (int i = 0; i < src.length; i++) {       

               int v = src[i] & 0xFF;       

               String hv = Integer.toHexString(v);       

               if (hv.length() < 2) {       

                   stringBuilder.append(0);       

               }       

               stringBuilder.append(hv);       

           }       

           return stringBuilder.toString().toUpperCase();       

       }
    
    
    /**
	 * wang zhi qiang
	 * @param hexString
	 * @return byte
	 */
	
	public static byte hexStringToBytes(String hexString) { 
		
	    if (hexString == null || hexString.equals("")) {  
	        return 0;  
	    } 
	    
	    if(hexString.length()==1){
	    	hexString="0"+hexString;
	    }
	    hexString = hexString.toUpperCase();
	    int length = hexString.length() / 2;  
	    char[] hexChars = hexString.toCharArray();  
	    byte[] d = new byte[length];  
	    for (int i = 0; i < length; i++) {  
	        int pos = i * 2;  
	        d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
	    }  
	    return d[0];  
	} 
	
	public static byte charToByte(char c) {  
		return (byte) "0123456789ABCDEF".indexOf(c);  
	} 
	
	
	public static byte[] getDoubleByteArray(int temInt) {
		byte[] tem = new byte[2];
		if (temInt > 0 && temInt < 65535) {
			if (temInt < 256) {
				tem[0] = (byte) 0x00;
				tem[1] = hexStringToBytes(Integer
						.toHexString(temInt));
			} else {
				String[] hexString = CommonUtil.get256HEX(temInt);
				tem[0]=hexStringToBytes(hexString[0]);
				tem[1]=hexStringToBytes(hexString[1]);
			}
			
		}else{
			tem[0]=(byte) 0x00;
			tem[1]=(byte) 0x00;
		}
		return tem;
	}
	
	public static byte getSingleByte(int temInt) {
		return hexStringToBytes(Integer.toHexString(temInt));
	}
	
	
		/**
		 *   ��ȡ
		 */
		public static String[]get256HEX(int no) {
			String[] hext = new String[2];
			if(no>255){
				hext[0]=Integer.toHexString(no/256);
				hext[1]=Integer.toHexString(no%256);
			}
			return hext;
		}
		
		
	/**
	 * 
	 * @param buffer
	 * @return ��ȡʮ������
	 */

	public static String getHexStringByByteArray(byte[] buffer) {
		StringBuilder stringBuilder = new StringBuilder("");
		for (int i = 0; i < 22; i++) {
			int v = buffer[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString().toUpperCase();

	}
	
	/**
	 * �жϵ�ǰӦ�ó�����ǰ̨���Ǻ�̨
	 * 
	 * @param context
	 * @return
	 */

	public static boolean isApplicationBroughtToBackground(final Context context) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasks = am.getRunningTasks(1);
		if (!tasks.isEmpty()) {
			ComponentName topActivity = tasks.get(0).topActivity;
			if (!topActivity.getPackageName().equals(context.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isBackground(Context context) {

		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		for (RunningAppProcessInfo appProcess : appProcesses) {
			if (appProcess.processName.equals(context.getPackageName())) {
				if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
					Log.i(String.format("Background App:",
							appProcess.processName), "");
					return true;
				} else {
					Log.i(String.format("Foreground App:",
							appProcess.processName), "");
					return false;
				}
			}
		}
		return false;
	}

	public static boolean checkSDcard() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 
	 * @param context
	 * @param pakageName
	 * @return APP�汾��
	 */
	public static int getVersionCode(Context context, String pakageName) {
		int versionCode = 0;
		try {
			versionCode = context.getPackageManager().getPackageInfo(
					pakageName, 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	/**
	 * �������Ƿ�������
	 */
	public static boolean isMyServiceRunning(Context context, String serviceName) {
		ActivityManager manager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (serviceName.equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * �ݹ�ɾ���ļ����ļ���
	 * 
	 * @param file
	 *            Ҫɾ���ĸ�Ŀ¼
	 */
	public static void RecursionDeleteFile(File file) {
		if (file.isFile()) {
			file.delete();
			return;
		}
		if (file.isDirectory()) {
			File[] childFile = file.listFiles();
			if (childFile == null || childFile.length == 0) {
				file.delete();
				return;
			}
			for (File f : childFile) {
				RecursionDeleteFile(f);
			}
			file.delete();
		}
	}
   
	/**
	 *  ��⵱ǰ����ʱ��������
	 */
	private static boolean isServiceRunning(Context context,String serviceName) {
	    ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
	        if (serviceName.equals(service.service.getClassName())) {
	            return true;
	        }
	    }
	    return false;
	}


	
	/**
	 * ��������Ƿ��Ѿ�����
	 */
	public static boolean checkNetworkConnection(Context context) {
		final ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		final android.net.NetworkInfo wifi = connMgr
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		final android.net.NetworkInfo mobile = connMgr
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		if (wifi.isAvailable() || mobile.isAvailable())
			return true;
		else
			return false;
	}

	/**
	 * �жϵ�ǰ���еĳ���
	 */
	public static boolean checkCurrentTask(Context context, String pakageName) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
		String packageName = cn.getPackageName();

		if (packageName != null && packageName.equals(pakageName)) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * �ж�activity�Ƿ��������ʾ 
	 */
	public static boolean checkCurrentActivity(Context context, String activityName) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
		String packageName = cn.getShortClassName();
		L.v(packageName);
		if (packageName != null && packageName.equals(activityName)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * ���ñ�������
	 * 
	 * @param Language
	 * @return
	 */
	public static boolean setLocalLanguage(String Language, Context context) {
		Configuration config = context.getResources().getConfiguration();
		DisplayMetrics dm = context.getResources().getDisplayMetrics();
		if ("CHINESE".equals(Language)) {
			config.locale = Locale.SIMPLIFIED_CHINESE;
		} else if ("ENGLISH".equals(Language)) {
			config.locale = Locale.ENGLISH;
		} else {
			config.locale = Locale.SIMPLIFIED_CHINESE;
		}
		context.getResources().updateConfiguration(config, dm);
		return true;
	}

	public static boolean checkFileExits(String path) {
		L.v(path);
		File file = new File(path);
		if (file.exists()) {
			return true;
		} else {
			return false;
		}
	}

	// ====================================================��ȡ�豸====================================================================
	/**
	 * ��ȡ��ǰϵͳsdk�汾
	 */
	public static int getSystemSdkVersion() {
		int versionCode = android.os.Build.VERSION.SDK_INT;
		return versionCode;
	}

	public static String getDeviceModel() {
		String phoneName = android.os.Build.MODEL;
		return phoneName;
	}

	// ============================================================================================================================


	// ��ȡ·�����µ�ͼƬ����
	public static List<String> getImgUriList(String imgPath) {
		List<String> imgPathList = new ArrayList<String>();
		if (CommonUtil.checkFileExits(imgPath)) {
			File filePath = new File(imgPath);
			File[] files = filePath.listFiles();
			for (File file : files) {
				if (file.getName().endsWith(".jpg")) {
					imgPathList.add(file.getAbsolutePath());
					System.out.println("��ʾͼƬ�ļ�"+ file.getAbsolutePath());
				}
			}
		}
		return imgPathList;
	}
	

	public static int Dp2Px(Context context, float dp) {  
	    final float scale = context.getResources().getDisplayMetrics().density;  
	    return (int) (dp * scale + 0.5f);  
	}  

	public static int Px2Dp(Context context, float px) {  
	    final float scale = context.getResources().getDisplayMetrics().density;  
	    return (int) (px / scale + 0.5f);  
	}


	public static boolean isInstall(String packageName,Context context) {
		
		PackageInfo packageInfo;
		
		try {
			packageInfo = context.getPackageManager().getPackageInfo(packageName,
					0);
		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}
		if (packageInfo == null) {
			return false;
		} else {
			return true;
		}
	}  
   
	public static String getAndroidDeviceUnique(Context context){
		return Secure.getString(context.getContentResolver(),Secure.ANDROID_ID);
	}
	




	public static final String removeBOM(String data) {

		if (TextUtils.isEmpty(data)) {

			return data;

		}

		if (data.startsWith("\ufeff")) {

			return data.substring(1);

		} else {

			return data;

		}
		

}

	/**
	 * 
	 * @param str
	 * @return  �ж����������Ƿ�ΪIP trueΪ�棬falseΪ��
	 */
	public static boolean isIP(String str) {
		Pattern pattern = Pattern.compile("\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])" +
				"\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\." +
				"((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\." +
				"((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b");
		return pattern.matcher(str).matches();
	}

	/*
	 * @param str Դ�ַ���ת�����ֽ�������ַ���
	 * 
	 * @return
	 */
	public static byte[] StringToByte(String str) {
		return StringToByte(str, "UTF-8");
	}

	/**
	 * UTF-8 һ������ռ�����ֽ�
	 * 
	 * @param str
	 *            Դ�ַ��� ת�����ֽ�������ַ���
	 * @return
	 */
	public static byte[] StringToByte(String str, String charEncode) {
		byte[] destObj = null;
		try {
			if (null == str || str.trim().equals("")) {
				destObj = new byte[0];
				return destObj;
			} else {
				destObj = str.getBytes(charEncode);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return destObj;
	}

}
